package com.zaofan.dao;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zaofan.bean.AppyOpen;
import com.zaofan.constant.StateConstant;
import com.zaofan.dao.base.DaoSupportImpl;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.SqlBuilderUtils;

public class AppyOpenDao extends DaoSupportImpl<AppyOpen> {

	public void setState(AppyOpen appyOpen) {
		try {
			String sql = "update " + AppyOpen.class.getSimpleName().toLowerCase() + " set state = "
					+ appyOpen.getState() + ",mark = '" + appyOpen.getMark() + "' where id = " + appyOpen.getId();
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(getDataSource());
			runner.update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public Integer addAppyOpen(AppyOpen appyOpen) {
		QueryRunner runner = new QueryRunner(getDataSource());
		Connection conn = C3p0DataSourceUtils.getConnection();
		try {
			String sql = SqlBuilderUtils.builderInsertSql(AppyOpen.class, appyOpen);
			System.err.println(sql);
			runner.update(conn, sql);
			// 获取新增记录的自增主键
			try {
				Long id = (Long) runner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler<Long>());
				return id.intValue();
			} catch (Exception e) {
				BigInteger id = (BigInteger) runner.query(conn, "SELECT LAST_INSERT_ID()",
						new ScalarHandler<BigInteger>());
				return id.intValue();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	public List<AppyOpen> findByNameLike(String key) {
		try {
			String sql = "select * from " + AppyOpen.class.getSimpleName().toLowerCase() + " where state = "
					+ StateConstant.APPY_STATE_OK + " and builderName like '%" + key + "%'";
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(getDataSource());
			return runner.query(sql, new BeanListHandler<>(AppyOpen.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

}
